/**
 * 
 */
package edu.arizona.eller.mis.liferoulette.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import edu.arizona.eller.mis.liferoulette.entity.UserPreference;

/**
 * @author Blaine Boule - blaineb@email.arizona.edu
 *
 */
public class UserPreferenceDAO extends BaseDAO {
	public static final String _USER_PREFERENCE_TABLE = "USER_PREFERENCES";
	
	public static final String _CREATE_STATEMENT = "CREATE TABLE " + _USER_PREFERENCE_TABLE  +
			" (id INTEGER PRIMARY KEY AUTOINCREMENT, label text not null, value text not null)";
	
	public UserPreferenceDAO(Context context){
		super(context);
	}
	
	public List<UserPreference> getUserPreferences() {
		List<UserPreference> list = new ArrayList<UserPreference>();
		
		Cursor cursor = db.query(_USER_PREFERENCE_TABLE, new String[] { "id", "label", "value" },  null, null, null, null, null);
		if(cursor.moveToFirst()){
			//return false if empty
			do{
				UserPreference up = new UserPreference(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
				list.add(up);
			}while(cursor.moveToNext());
			//This method will return false if the cursor is already past the last entry in the result set.
			/* 
			id 	label 			value
			1	MILES_SETTING	5
			2	USEFB_SETTING 	TRUE	
			3	USESMS_SETTING	TRUE
			 */
			if(cursor!=null && !cursor.isClosed()){
				cursor.close();
			}
		}
		return list;
	}
	
	public UserPreference findById(Integer id){
		UserPreference up = null;
		Cursor cursor = db.query(_USER_PREFERENCE_TABLE, new String[] { "id", "label", "value" },  UserPreference._id + "=" + id, null, null, null, null);
		
		if(cursor.moveToFirst()){
			up = new UserPreference(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
		}
		
		return up;
	}
	
	public int update(UserPreference up){
		ContentValues update = new ContentValues();
	
		//update.put(UserPreference._label, up.getLabel());
		update.put(UserPreference._value, up.getValue());
		
		return db.update(_USER_PREFERENCE_TABLE, update, UserPreference._id + "=" + up.getId(), null);
	}
	
	public long insert(UserPreference up) {
	
		ContentValues insert = new ContentValues();
		insert.put(UserPreference._label, up.getLabel());
		insert.put(UserPreference._value, up.getValue());
		
		return db.insert(_USER_PREFERENCE_TABLE, null, insert);	
	}
	
	public int delete(UserPreference up){
		
		return db.delete(_USER_PREFERENCE_TABLE, UserPreference._id + "=" + up.getId(), null);
	}
}
